package com.framework.interceptor;

import com.biz.model.Pmodel.base.PbaseUser;
import com.biz.service.MService.user.UserServiceI;
import com.biz.utils.ConfigUtil;
import com.biz.utils.StringUtil;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;

/**
 *
 */
public class LoginHandlerInterceptor extends HandlerInterceptorAdapter {
	@Resource(name = "userService")
	private UserServiceI userService;

	@Override
	public boolean preHandle(HttpServletRequest request,
							 HttpServletResponse response, Object handler) throws Exception {
		String path = request.getServletPath();
		String nopatP = ConfigUtil.get("NO_INTERCEPTOR_PATH");
		if (path.matches(nopatP)) {
			return true;
		} else {
			HttpSession session = request.getSession();

//			session.setAttribute(ConfigUtil.get("SESSION_OPEN_ID"),
//					"oh8S407S3nW4h4MmXK2Sx8AqAtig");

			//从session中获取openId,userId
			String openId = String.valueOf(session
					.getAttribute(ConfigUtil.get("SESSION_OPEN_ID")));
			String userId = String.valueOf(session
					.getAttribute(ConfigUtil.get("SESSION_USER_ID")));

			if (StringUtil.isNullOrEmpty(openId) || "null".equals(openId))
			{
				// TODO: openId is empty ,getByApi.
				String resultUrl = request.getRequestURL().toString();
				String param = request.getQueryString();
				if (param != null) {
					resultUrl += "?" + param;
				}
				try {
					resultUrl = java.net.URLEncoder.encode(resultUrl,"utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				String contextPath =ConfigUtil.get("SYS_URL");
				response.sendRedirect(contextPath + "/wx_oauth2.ac?resultUrl="+ resultUrl);
				return true;
			}

//			if (StringUtil.isNullOrEmpty(userId) || "null".equals(userId))
//			{
				// TODO: get userInfo by openId.
				PbaseUser pbaseUser = userService.queryUserInfoByOpenId(openId);
				if(pbaseUser!=null)
				{
					session.setAttribute(ConfigUtil.get("SESSION_USER_ID"), pbaseUser.getId());
					session.setAttribute(ConfigUtil.get("SESSION_USER_PHONE"),
							pbaseUser.getPhone() != null ? pbaseUser.getPhone() : "");
				}else{
					// TODO: save user by openId , return user
					PbaseUser pbaseUserSave = userService.saveUserInfoByOpenIdAndReturn(openId);
					session.setAttribute(ConfigUtil.get("SESSION_USER_ID"), pbaseUserSave.getId());
					session.setAttribute(ConfigUtil.get("SESSION_USER_PHONE"),
							pbaseUserSave.getPhone() != null ? pbaseUserSave.getPhone() : "");
				}
//			}
			return true;
		}
	}

}
